/*
 * Copyright (c) 2012 Xilinx, Inc.  All rights reserved.
 *
 * Xilinx, Inc.
 * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
 * COURTESY TO YOU.  BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
 * ONE POSSIBLE   IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
 * STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
 * IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
 * FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
 * XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
 * THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
 * ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
 * FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 */

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define MAX_SIZE 512
int main()
{
	int sockfd,sockfd_local;
	unsigned char buf[MAX_SIZE]={1,2,3,4,5,6,7,8,9};
	unsigned char recv_buf[MAX_SIZE]={0};
    struct sockaddr_in serv_addr;
    int len = sizeof(serv_addr);
    bzero(&serv_addr, len);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(3212);
    serv_addr.sin_addr.s_addr =  inet_addr("192.168.1.98");
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        printf("create socket failed! \n");
        exit(1);
    }

    struct sockaddr_in local_addr;
	bzero(&local_addr, len);
	local_addr.sin_family = AF_INET;
	local_addr.sin_port = htons(3213);
	local_addr.sin_addr.s_addr =  inet_addr("192.168.1.10");
	sockfd_local = socket(AF_INET, SOCK_DGRAM, 0);
	if (sockfd_local < 0)
	{
		 printf("create socket failed! \n");
		 exit(1);
	}

    struct timeval timeOut;
    timeOut.tv_sec = 1;
    timeOut.tv_usec = 0;
    if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeOut, sizeof(timeOut)) < 0)
		printf("time out setting failed\n");
    if(setsockopt(sockfd_local, SOL_SOCKET, SO_RCVTIMEO, &timeOut, sizeof(timeOut)) < 0)
		printf("time out setting failed\n");

    if (bind(sockfd_local, (struct sockaddr *)&local_addr, len) < 0)
    {
        printf("bind error\n");
        exit(1);
    }

    while (1)
    {
        if(sendto(sockfd, buf, 20, 0, (const struct sockaddr *)&serv_addr, len) < 0)
            fprintf(stderr, "send error: %s\n", strerror(errno));

        if(recvfrom(sockfd_local, recv_buf, MAX_SIZE, 0, (struct sockaddr *)&serv_addr, (socklen_t *)&len) < 0)
            printf("udp not recv data!\n");
        else {
        	printf("recv %s\n", recv_buf);
        }
        memset(recv_buf, 0, MAX_SIZE);
    }
    close(sockfd);
    return 0;
}
